/**
 * 校验手机号
 * @type {{validator: checkMobile.validator, trigger: string}}
 */
const checkMobile = {
  trigger: 'blur',
  validator: (rule, value, callback) => {
    if (!value) {
      return callback()
    }
    if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(value))) {
      callback(new Error('手机号码有误，请重填'))
    } else {
      callback()
    }
  }
}

/**
 * 必填
 * @type {{validator: required.validator, required: boolean}}
 */
const required = {
  trigger: ['change', 'blur'],
  required: true,
  validator: (rule, value, callback) => {
    if (value === '' || value === undefined || value === null) {
      callback(new Error('不能为空'))
    } else {
      callback()
    }
  }
}

/**
 * 必填
 * @type {{validator: required.validator, required: boolean}}
 */
const requiredSelect = {
  required: true,
  validator: (rule, value, callback) => {
    if (value === '' || value === undefined || value === null) {
      callback(new Error('请选择'))
    } else {
      callback()
    }
  }
}

/**
 * 整数验证
 * @type {{validator: numRules.validator, trigger: string}}
 */
const numRules = {
  trigger: 'blur',
  validator: (rule, value, callback) => {
    const te = /^[0-9]+$/
    if (value !== undefined && value !== '' && value !== null && !te.test(value)) {
      callback(new Error('请输入整数'))
    } else {
      callback()
    }
  }
}
/**
 * 浮点数验证
 * @type {{validator: numFloatRules.validator, trigger: string}}
 */
const numFloatRules = {
  trigger: 'change',
  validator: (rule, value, callback) => {
    const te = /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/
    const zh = /^[1-9]\d*|0$/
    if (value !== undefined && value !== '' && value !== null && (!te.test(value))) {
      if (!zh.test(value)) {
        callback(new Error('请输入正浮点数'))
      } else {
        callback()
      }
    } else {
      callback()
    }
  }
}
const validators = {
  /**
   * 可区分全角字符/半角字符的长度校验。
   * @param min
   * @param max
   * @returns {Function}
   */
  length ({ min = 0, max = 100000000 }) {
    return function (rule, value, callback) {
      // 将一个全角字符替换成两个半角字符，以得到真实长度。
      callback(new Error('输入长度应在' + min + '到' + max + '个字符之间！'))
    }
  }
}

const moneyRules = {
  trigger: 'change',
  validator: (rule, value, callback) => {
    if (value) {
      // 用于金额验证 支持负数
      if (!new RegExp('^(([+-])?([0-9]+(\\.[0-9]{1,2})?))$').test(value)) {
        callback(new Error('请输入整数或两位小数'))
      } else {
        if (value > 999999999.99) {
          callback(new Error('最大到999999999.99'))
        } else {
          callback()
        }
      }
    } else {
      callback()
    }
  }
}

export default {
  required,
  checkMobile,
  numRules,
  numFloatRules,
  validators,
  requiredSelect,
  moneyRules
}
